﻿using System;
using System.Data;
using System.IO;
using System.Net;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Xml;
using System.Collections;
using System.Collections.Generic;

using Rmlife.Control;
using Rmlife.Common;
using Rmlife.Site;
using Rmlife.Web.AutoUpdateManager;
using Button = Rmlife.Control.Button;
using DropDownList = Rmlife.Control.DropDownList;
using TextBox = Rmlife.Control.TextBox;
using Rmlife.Config;
using Rmlife.Data;
using Rmlife.Model;


namespace Rmlife.Web
{
    /// <summary>
    /// 快捷操作
    /// </summary>

    public partial class shortcut : PageBase
    {
        public Hashtable CompanyStatTable = new Hashtable();
        public string filenamelist = "";
        protected string upgradeInfo = "";
        protected bool isNew = false;
        protected bool isHotFix = false;
        //public List<PrivateMessageInfo> pmlist;
        
        public bool havePm = false;

        protected void Page_Load(object sender, EventArgs e)
        {
        
            //Page.Title = productname;
            /*
            #region 友好提示
            if (!BaseConfigs.GetDogExist)
                Warning.Text = "<IMG alt=\"提示:\" src=\"../images/warning.gif\" align=\"absMiddle\" border=\"0\" >&nbsp;<font color=\"red\">系统未检测到服务端加密狗，这会影响数据的正常传输<br />，请安装并检查服务端加密狗设置！</font>";
            else
                Warning.Text = "<IMG alt=\"提示:\" src=\"../images/hint.gif\" align=\"absMiddle\" border=\"0\" >&nbsp;<font color=\"green\">服务端加密狗已正确安装</font>";
            #endregion
             * */

            if (!IsPostBack)
            {
                #region //
                //CompanyStatTable = Companys.GetCompanyStat(base.accountgroupid);


                //string companygroupid = string.Empty;

                //if (CheckMyRole())
                //{
                //    companygroupid = base.accountgroupid;
                //}
                //pmlist = PrivateMessages.GetPrivateMessageCollectionForIndex(companygroupid, PrivateMessageObject.Group, 5, 1, 1);
                //havePm = pmlist.Count > 0;
                //pp.DataSource = pmlist;
                //pp.DataBind();

                ///*AlarmStatusCount方法的第一个参数用于查询是否CCIC("Z")，辑控库("C")，一般布控("G"),为空的话则是查询全部,第2参数是状态值，0=未处理，1=已处理，2=正在处理，具体查询字典库*/
                //string strWhere = "";
                //if (CheckMyRole())
                //{
                //    strWhere += " and tCompanyGroup.sGroupID = '" + accountgroupid + "' and (tViolateAccess.sGroupID = '" + accountgroupid + "' or tViolateAccess.sGroupID = '0')";

                //}


                //GetAlarmInfo(this.AlarmCount, PolicyConfigProvider.GetInstance().AlarmStatusCount("G", 0, strWhere).ToString(), "《布控策略》", "../CaseManage/PolicyAlarm.aspx?Status=0");
                //GetAlarmInfo(this.CCICAlarmCount, PolicyConfigProvider.GetInstance().AlarmStatusCount("Z", 0, strWhere).ToString(), "《CCIC》", "../CaseManage/Ccic_Alarm.aspx?Status=0");
                //GetAlarmInfo(this.WatchingAlarmCount, PolicyConfigProvider.GetInstance().AlarmStatusCount("C", 0, strWhere).ToString(), "《辑控库》", "../CaseManage/Watching_lAlarm.aspx?Status=0");

                #endregion 
            }

        }
        

        private void GetAlarmInfo(Label lbl,string alarmCount,string strChar,string strLink)
        {
            if (alarmCount == "0")
            {
                lbl.Text = " 目前还有 " + "<span class='largeNumberText'>" + alarmCount + "</span>" + " 条符合条件的" + strChar + "报警未处理";
            }
            else
            {
                lbl.Text = " 目前还有 " + "<span class='largeNumberText'><a href='" + strLink + "' style='text-decoration: none;color: rgb(255, 0, 0);'> " + alarmCount + " </a></span>" + " 条符合条件的" + strChar + "报警未处理";
            }
            
        }

        private void LoadUpgradeInfo()
        {

            if (!IsPostBack)
            {
                try
                {

                    //合并升级信息
                    MergeUpgradeInfo();
                    //获取官方升级版本列表，并存放到本地upgrade/upgradeini.config中
                    AutoUpdate autoUpdate = new AutoUpdate();
                    string fileContnet = autoUpdate.GetVersionList();
                    StreamWriter writer = new StreamWriter(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "upgradeini.config"));
                    writer.Write(fileContnet.Replace("\n", "\r\n"));
                    writer.Close();

                    //取本地更新版本号与官方的最新版本号比较，如果官方有更新，则提示有升级
                    XmlDocument lastupdate = new XmlDocument();
                    lastupdate.Load(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "localupgradeini.config"));
                    DateTime build = StrToDateTime(lastupdate.SelectSingleNode("/localupgrade/requiredupgrade").InnerText);
                    XmlDocument currentupdate = new XmlDocument();
                    currentupdate.LoadXml(fileContnet);
                    XmlNodeList items = currentupdate.SelectNodes("/versionlist/" + BaseConfigs.GetDbType.ToLower() + "/requiredupgrade/item");
                    XmlNode lastItem = items.Item(items.Count - 1);
                    //DateTime version = StrToDateTime(items.Item(items.Count - 1).FirstChild.InnerText);
                    DateTime version = StrToDateTime(lastItem["version"].InnerText);
                    isNew = version > build;
                    if (isNew)
                    {
                        //upgradeInfo = "检测到最新版本：" + version.ToShortDateString() + "<br />" + items.Item(items.Count - 1).LastChild.InnerText + "<br />";
                        upgradeInfo = "<span style='font-size:16px;'>检测到最新版本：" + lastItem["versiondescription"].InnerText + "</span><br /><span style='padding:3px 0px 3px 10px;display:block;'>" + lastItem["description"].InnerText + "</span>";
                    }

                    XmlNodeList local = lastupdate.SelectNodes("/localupgrade/optionalupgrade/vm" + Utils.GetAssemblyVersion() + "/item");
                    XmlNodeList service = currentupdate.SelectNodes("/versionlist/" + BaseConfigs.GetDbType.ToLower() + "/optionalupgrade/vm" + Utils.GetAssemblyVersion() + "/item");
                    string hotfix = "";
                    foreach (XmlNode serviceitem in service)
                    {
                        bool exist = false;
                        foreach (XmlNode localitem in local)
                        {
                            if (serviceitem.FirstChild.InnerText == localitem.InnerText)
                            {
                                exist = true;
                                break;
                            }
                        }
                        if (!exist)
                        {
                            isHotFix = true;
                            hotfix += serviceitem["versiondescription"].InnerText + "<br />";
                        }

                    }

                    if (hotfix != "")
                    {
                        upgradeInfo += "<span style='font-size:16px;'>检测到最新补丁：</span><br /><span style='padding:3px 0px 3px 10px;display:block;'>" + hotfix + "</span>";
                    }

                    if (isNew || isHotFix)
                    {
                        base.RegisterStartupScript("", "<script type='text/javascript'>\r\nshowInfo();\r\n</script>\r\n");
                    }
                }
                catch
                {
                    ;
                }
            }
        }

        private void MergeUpgradeInfo()
        {
            if (!File.Exists(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "commonupgradeini.config")))
            {
                return;
            }
            XmlDocument configfile = new XmlDocument();
            //读取普通升级的信息文件
            string requiredupgradeversion = "";
            string optionalupgradeversion = "";
            configfile.Load(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "commonupgradeini.config"));
            if (configfile.SelectSingleNode("/requiredupgrade") != null)
            {
                requiredupgradeversion = configfile.SelectSingleNode("/requiredupgrade").InnerText;
            }
            else
            {
                optionalupgradeversion = configfile.SelectSingleNode("/optionalupgrade").InnerText;
            }
            File.Delete(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "commonupgradeini.config"));

            configfile.Load(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "localupgradeini.config"));
            if (requiredupgradeversion != "")
            {
                if (StrToDateTime(configfile.SelectSingleNode("/localupgrade/requiredupgrade").InnerText) >= StrToDateTime(requiredupgradeversion))
                {
                    return;
                }
                configfile.SelectSingleNode("/localupgrade/requiredupgrade").InnerText = requiredupgradeversion;
            }
            else
            {
                XmlNode vmver = configfile.SelectSingleNode("/localupgrade/optionalupgrade/vm" + Utils.GetAssemblyVersion());
                if (vmver == null)
                {
                    vmver = configfile.CreateElement("vm" + Utils.GetAssemblyVersion());
                }
                XmlElement item = configfile.CreateElement("item");
                item.InnerText = optionalupgradeversion;
                vmver.AppendChild(item);
                configfile.SelectSingleNode("/localupgrade/optionalupgrade").AppendChild(vmver);
            }
            configfile.Save(Utils.GetMapPath(WebConfigs.Paths.DataRoot.ToLower() + "localupgradeini.config"));
        }

        private DateTime StrToDateTime(string str)
        {
            string date = str.Substring(0, 4) + "-" + str.Substring(4, 2) + "-" + str.Substring(6, 2);
            if (str.Length == 8)
            {
                date += " 00:00:00";
            }
            else
            {
                date += " " + str.Substring(8, 2) + ":" + str.Substring(10, 2) + ":" + str.Substring(12, 2);
            }
            return Convert.ToDateTime(date);
        }

        public void LinkVersionPage()
        {

        }

        private void UpdateCache_Click(object sender, EventArgs e)
        {
            #region 更新所有缓存

            //if (this.CheckCookie())
            //{
            //    Caches.ReSetAllCache();
            //    base.RegisterStartupScript("PAGE", "window.location.href='shortcut.aspx';");
            //}

            #endregion
        }

        #region Web 窗体设计器生成的代码

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);
        }

        #endregion


        public string ShowStatus(string status)
        {
            switch (status)
            {
                case "0":
                    return "未处理";

                case "1":
                    return "已处理";

                case "2":
                    return "处理中";

                case "-1":
                    return "作废";

            }
            return "未处理";
        }

    }
}